package com.itheima.bigevent.controller;

import com.itheima.bigevent.pojo.Article;
import com.itheima.bigevent.pojo.Category;
import com.itheima.bigevent.pojo.PageBean;
import com.itheima.bigevent.pojo.Result;
import com.itheima.bigevent.service.ArticleService;
import com.itheima.bigevent.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增文章
     *
     * @param article
     * @return
     */
    @PostMapping
    public Result add(@RequestBody @Validated(Article.Add.class) Article article) {
        Category category = categoryService.detail(article.getCategoryId());
        if (category == null || category.getId() == null || category.getId() < 1) {
            return Result.error("文章所属分类不存在");
        }

        if (articleService.add(article) > 0) {
            return Result.success();
        } else {
            return Result.error("新增文章失败");
        }
    }

    /**
     * 分页获取文章列表
     *
     * @param pageNum    页码
     * @param pageSize   页面大小
     * @param categoryId 分类ID
     * @param state      文章状态，只能是“已发布”或“草稿”
     * @return 带有分页信息的文章列表
     */
    @GetMapping
    public Result<PageBean<Article>> list(
            @RequestParam(required = true) Integer pageNum,
            @RequestParam(required = true) Integer pageSize,
            @RequestParam(required = false) String categoryId,
            @RequestParam(required = false) String state
    ) {
       PageBean<Article> pageBean = articleService.list(pageNum, pageSize, categoryId, state);
       return Result.success(pageBean);
    }
}
